package com.lzm.easyexcel.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author liuzemin
 * @date 2023/8/10 0010 22:03
 * @description
 */
public class EasyExcelUtil {

    /**
     * 导入
     * @param file 文件
     * @param aClass 接导入数据的对象
     * @param sheetNo 第几个sheet
     * @return
     */
    public static Object read(File file, Class<? extends ExcelIndex> aClass, Integer sheetNo){
        EasyExcelListener listener = new EasyExcelListener();
        EasyExcel.read(file, aClass, listener).sheet(sheetNo - 1).autoTrim(true).doRead();
        return listener.getData();
    }

    /**
     * 导入
     * @param multipartFile 文件
     * @param aClass 接导入数据的对象
     * @param sheetNo 第几个sheet
     * @return
     */
    public static Object read(MultipartFile multipartFile, Class<? extends ExcelIndex> aClass, Integer sheetNo) throws IOException {
        EasyExcelListener listener = new EasyExcelListener();
        EasyExcel.read(multipartFile.getInputStream(), aClass, listener).sheet(sheetNo- 1).autoTrim(true).doRead();
        return listener.getData();
    }

    /**
     * 导出
     * @param fileName 文件名
     * @param sheetName sheet名
     * @param aClass 导出数据的对象
     * @param data 导出的数据
     * @param response
     */
    public static void write(String fileName, String sheetName, Class<?> aClass, List<?> data, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  //xlsx
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName + DateUtil.format(new Date(), "yyyyMMddHHmmss"), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), aClass)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet(sheetName).doWrite(data);
    }
}
